<script setup>
import { User, Lock, Message, EditPen } from '@element-plus/icons-vue'
import router from '@/router'
import '@/util/baseStyle.css'
import { reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { post } from '@/util/axios';

const form = reactive({
  username: '',
  password: '',
  passwordRepeat: '',
  email: '',
  code: ''
})


const validateUsernamne = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入用户名'))
  } else if (!/^[a-zA-Z0-9\u4e00-\u9fa5]+$/.test(value)) {
    callback(new Error('用户名不能包含特殊字符'))
  } else {
    callback()
  }
}

const validatePassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else if (value !== form.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const rules = {
  username: [
    { validator: validateUsernamne, trigger: ['blur', 'change']},
    { min:6, max: 18, message: '用户名的长度必须是6-18个字符', trigger: 'blur'}
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur'},
    { min:6, max: 18, message: '密码的长度必须是6-18个字符', trigger: 'blur'}
  ],
  passwordRepeat: [
    { validator: validatePassword, trigger: 'blur'}
  ],
  email: [
    { required: true, message: '请输入电子邮件地址', trigger: 'blur'},
    { type: 'email', message:'请输入合法的电子邮件地址', trigger: ['blur', 'change']}
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur'}
  ]
}

const isEmailValid = ref(false)
const onValidate = (prop, isValid) => {
  if (prop === 'email') 
    isEmailValid.value = isValid
}

const formRef = ref()
const register = () => {
  formRef.value.validate((isValid) => {
    if (isValid) {
      post('/api/auth/register', {
        username: form.username,
        password: form.password,
        email: form.email,
        code: form.code
      }, (message) => {
        ElMessage.success(message)
        router.push("/")
      })
    } else {
      ElMessage.warning('请填写注册信息')
    }
  })
}


const coldTime = ref(0)
const validateEmail = () => {
  coldTime.value = 60
 
  post('/api/auth/valid-register-email', {
    email: form.email
  }, (message) => {
    ElMessage.success(message)
    setInterval(() => {coldTime.value--}, 1000)
  }, (message) => { 
    ElMessage.warning(message)
    coldTime.value = 0 
  })
}
</script>

<template>
  <div style="text-align: center; margin: 0 20px;" v-cloak>
    <div class="bs-title">
      <div style="font-size: 25px; font-weight: 600;">Join Us</div>
    </div>

    <div style="margin-top: 50px;">
      <el-form :model="form" :rules="rules" @validate="onValidate" ref="formRef">
        <el-form-item prop="username">
          <el-input v-model="form.username" type="text" placeholder="username" >
            <template #prefix>
              <el-icon><User/></el-icon>
            </template>  
          </el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input v-model="form.password" :maxlength="18" type="password" placeholder="password" >
            <template #prefix>
              <el-icon><Lock/></el-icon>
            </template>  
          </el-input>
        </el-form-item>

        <el-form-item prop="passwordRepeat">
          <el-input v-model="form.passwordRepeat" :maxlength="18" type="password" placeholder="duplicate password" >
            <template #prefix>
              <el-icon><Lock/></el-icon>
            </template>  
          </el-input> 
        </el-form-item>

        <el-form-item prop="email">
          <el-input v-model="form.email" type="email" placeholder="bind your email" >
            <template #prefix>
              <el-icon><Message/></el-icon>
            </template>  
          </el-input> 
        </el-form-item>

        <el-form-item prop="code">
          <div style="display: flex; justify-content:space-between; width: 100%;">
            <el-input v-model="form.code" type="text" placeholder="received code"  :maxlength="6">
                <template #prefix>
                  <el-icon><EditPen/></el-icon> 
                </template>  
              </el-input>

              <el-button @click="validateEmail" class="btn" :class="{codeBtn: isEmailValid}"  
                        style="--bg: #b675b8; --cl: #fff; margin-left: 10px;" :disabled="!isEmailValid || coldTime > 0">
                {{coldTime > 0 ? `wait for ${coldTime}s` : "Send Code"}}
              </el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>

    <div style="margin-top: 80px;">
      <el-button @click="register" class="btn signBtn" style="--w: 300px; --bg: #986a99; --cl: #fff">Register Now</el-button>
    </div>

    <div style="font-size: 14px; margin-top: 15px;">
      <span style="color: grey;">Existing Account With </span>
      <el-link class="loginLink" :underline="false" @click="router.push('/')">Login Now</el-link>
    </div>
  </div>
</template>

<style scoped>
.btn{
  width: var(--w);
  background-color: var(--bg);
  color: var(--cl);
  outline: none;
  border: none;
  font-weight: 600;
}

.codeBtn:hover{
  background-color: #ca91cc;
}

.signBtn:hover{
  background-color: #b289b3;
}

.loginLink{
  vertical-align:text-top;
  color: #fd4aaa; 
  text-decoration:underline;
}
</style>
<style>
.el-button.is-disabled{
  background-color: #deb9df;
}
.el-button.is-disabled:hover{
  color: #fff;
  background-color: #deb9df;
}
</style>